package com.xiaofeng.pochi.shiro;


import com.xiaofeng.pochi.pojo.LoginUser;
import com.xiaofeng.pochi.pojo.ShopUser;
import com.xiaofeng.pochi.service.ShopUserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created with IntelliJ IDEA
 *
 * @Author: chc
 * @Date: 2022/08/21/20:28
 * @Description:
 */
@Component("shopUserRealm")
public class ShopUserRealm extends AuthorizingRealm {

    @Autowired
    private ShopUserService ShopUserService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UserToken userToken = (UserToken) authenticationToken;
        //拿到username，也就是我们的openid
        String username = userToken.getUsername();
        //根据openid去查询用户
        ShopUser shopUser = ShopUserService.getByOpenId(username);
        if (shopUser == null) {
            throw new AuthenticationException("用户不存在！");
        }
        //转换成loginuser
        LoginUser loginUser = shopUser.toLoginUser();
        return new SimpleAuthenticationInfo(loginUser,shopUser.getOpenId(),getName());
    }
}